﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cyss.Core.Api
{
    /// <summary>
    /// 用户功能权限管理
    /// </summary>
    public class PermissionAttribute : Attribute, IAsyncActionFilter
    {
        /// <summary>
        /// 权限code
        /// </summary>
        public string OperationType { set; get; }

        public string PageCode { set; get; }

        /// <summary>
        /// 权限说明
        /// </summary>
        public string Describe { set; get; }

        public PermissionAttribute()
        {
            this.PageCode=PageCode;
            this.OperationType=OperationType;
        }
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            OperateResult apiResponse = new OperateResult();
            var permissionVerification = IOCEngine.Resolve<IPermissionVerification>();
            if (!await permissionVerification.IsPermission(this.PageCode, this.OperationType))
            {
                apiResponse.CodeType=OperateResultCodeType.PermissionFail;
                apiResponse.IsSuccess = false;
                apiResponse.Message = "没有操作权限";
                context.Result = new JsonResult(apiResponse);
                return;
            }
            else
            {
                await next();
            }

        }
    }

}
